//
//  WbOauthController.swift
//  Weibo
//
//  Created by HH on 16/12/2.
//  Copyright © 2016年 Weibo. All rights reserved.
//

import UIKit
import SVProgressHUD

let AppKey = "1454736676"
let Redirect_uri = "http://www.baidu.com"
let AppSecret = "b4b5532cd5ae6f1dc2d46c25fe2ab920"




class WbOauthController: UIViewController {
    
    lazy private var webView = UIWebView()
    
    override func loadView() {
        
        view = webView
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        setupNavUI()
        
        loadRequest()
        // Do any additional setup after loading the view.
    }
    
    func setupNavUI(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, selector: #selector(cancelAction(sender:)))
        
        navigationItem.title = "微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", imageName: nil, target: self, selector: #selector(autoFillAction(sender:)), color: UIColor.darkGray)
    }
    
    @objc private func cancelAction(sender:UIButton){
        
        dismiss(animated: true, completion: nil)
    }
    
    private func loadRequest(){
        
        let url = URL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(Redirect_uri)")
        
        let urlRequest = URLRequest(url: url!)
        
        webView.loadRequest(urlRequest)
        
    }
    
    
    @objc private func autoFillAction(sender:UIButton){
        
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = '15539731602'; document.getElementById('passwd').value = 'mwq8856321'")
        
    }
    
    
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}


extension WbOauthController: UIWebViewDelegate{
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //http://www.baidu.com/?code=cb43c8ff6d5f2a08b22bd15c12abfcab
    
    //MARK:当将要开始加载的时候会调用这个方法
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.url else {
            return false
        }
        
        print(url)
    
        
        //判断开头是否为所需要字段
        if !url.absoluteString.hasPrefix(Redirect_uri) {
            return true
        }
        
        if let query = url.query, query.hasPrefix("code="){
            
            let startIndex = "code=".endIndex
            
            let code = query.substring(from: startIndex)
            
            print(code)
            
            
            WbUserAccountViewModel.sharedUserAccount.loadRequestAccess_token(code: code, complete: { (isSucess) in
                if isSucess {
                    print("登录成功")
                    
                    //注意!!先要dismiss再发送通知
                    self.dismiss(animated: true, completion: { 
                        NotificationCenter.default.post(name: NSNotification.Name(SwitchViewController), object: nil)
                    })
                    
                    
                }else{
                    print("登录失败")
                }
            })
            
        }
        
        
        return true
    }
    
    
    
}
